<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElSpace,
  ElSwitch,
  ElTable,
  ElTableColumn,
  ElTag,
} from "element-plus";
import { useRouter } from "vue-router";

import { examApi } from "@/api/modules/exam.api";
import { examRecordApi } from "@/api/modules/examRecord.api";
import { paperApi } from "@/api/modules/paper.api";
import { useCommonStore } from "@/store/common";
import {
  Calendar,
  Delete,
  Edit,
  Plus,
  Search,
  TrophyBase,
  View,
} from "@element-plus/icons-vue";
import type { IExam } from "@shared/types/exam";
import type { IPaper } from "@shared/types/paper";

const commonStore = useCommonStore();
const router = useRouter();
commonStore.header = "活动管理";

// 响应式数据
const loading = ref(false);
const tableData = ref<IExam[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(20);

// 搜索条件
const searchForm = reactive({
  keyword: "",
  status: "",
  creator: "",
});

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogType = ref<"create" | "edit" | "view">("create");

// 排名弹窗控制
const rankingDialogVisible = ref(false);
const rankingLoading = ref(false);
const currentExamInfo = ref<any>(null);
const rankingData = ref<any[]>([]);
const rankingSearchKeyword = ref("");

// 表单数据
const examForm = reactive<any>({
  exam_name: "",
  description: "",
  start_time: "",
  end_time: "",
  paper: "",
  is_enabled: true,
  participation_limit: 0,
  allow_retake: false,
});

// 表单验证规则
const formRules = {
  exam_name: [
    { required: true, message: "请输入活动名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "活动名称长度应在2-50字符之间",
      trigger: "blur",
    },
  ],
  start_time: [
    { required: true, message: "请选择开始时间", trigger: "change" },
  ],
  end_time: [{ required: true, message: "请选择结束时间", trigger: "change" }],
  paper: [{ required: true, message: "请选择试卷", trigger: "change" }],
};

// 可用试卷列表
const availablePapers = ref<IPaper[]>([]);

// 表单引用
const formRef = ref();

// 状态选项
const statusOptions = [
  { label: "启用", value: "enabled" },
  { label: "禁用", value: "disabled" },
];

// 获取状态标签类型
const getStatusType = (isEnabled: boolean) => {
  return isEnabled ? "success" : "danger";
};

// 获取状态文本
const getStatusText = (isEnabled: boolean) => {
  return isEnabled ? "启用" : "禁用";
};

// 获取考试状态（根据时间判断）
const getExamStatus = (exam: IExam) => {
  const now = new Date();
  const startTime = new Date(exam.start_time);
  const endTime = new Date(exam.end_time);

  if (!exam.is_enabled) return { text: "已禁用", type: "info" };
  if (now < startTime) return { text: "未开始", type: "warning" };
  if (now >= startTime && now <= endTime)
    return { text: "进行中", type: "success" };
  return { text: "已结束", type: "info" };
};

// 获取考试活动列表
const fetchExams = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    };
    const response = await examApi.getExamList(params);
    tableData.value = response.data.data;
    total.value = response.data.total_records;
  } catch (error) {
    console.error("获取考试活动列表失败:", error);
    ElMessage.error("获取考试活动列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取可用试卷列表
const fetchAvailablePapers = async () => {
  try {
    const response = await paperApi.getPaperList({
      status: "published",
      pageSize: 1000,
    });
    availablePapers.value = response.data.data;
  } catch (error) {
    console.error("获取可用试卷列表失败:", error);
    ElMessage.error("获取可用试卷列表失败");
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchExams();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: "",
    status: "",
    creator: "",
  });
  handleSearch();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchExams();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  fetchExams();
};

// 打开弹窗
const openDialog = (type: "create" | "edit" | "view", exam?: IExam) => {
  dialogType.value = type;
  dialogVisible.value = true;

  if (type === "create") {
    dialogTitle.value = "创建考试活动";
    Object.assign(examForm, {
      exam_name: "",
      description: "",
      start_time: "",
      end_time: "",
      paper: "",
      is_enabled: true,
      participation_limit: 0,
      allow_retake: false,
    });
  } else if (type === "edit" && exam) {
    dialogTitle.value = "编辑考试活动";
    Object.assign(examForm, {
      ...exam,
      paper:
        typeof exam.paper === "object" ? (exam.paper as any)._id : exam.paper,
    });
  } else if (type === "view" && exam) {
    dialogTitle.value = "考试活动详情";
    Object.assign(examForm, {
      ...exam,
      paper:
        typeof exam.paper === "object" ? (exam.paper as any)._id : exam.paper,
    });
  }
};

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
};

// 保存考试活动
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 验证时间逻辑
    if (new Date(examForm.end_time!) <= new Date(examForm.start_time!)) {
      ElMessage.error("结束时间必须晚于开始时间");
      return;
    }

    if (dialogType.value === "create") {
      await examApi.createExam(examForm);
      ElMessage.success("考试活动创建成功");
    } else {
      await examApi.updateExam(examForm._id!, examForm);
      ElMessage.success("考试活动更新成功");
    }

    closeDialog();
    fetchExams();
  } catch (error) {
    console.error("保存考试活动失败:", error);
    ElMessage.error("保存考试活动失败");
  }
};

// 删除考试活动
const handleDelete = async (exam: IExam) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除考试活动"${exam.exam_name}"吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await examApi.deleteExam(exam._id!);
    ElMessage.success("考试活动删除成功");
    fetchExams();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除考试活动失败:", error);
      ElMessage.error("删除考试活动失败");
    }
  }
};

// 启用/禁用考试活动
const handleStatusChange = async (exam: IExam, newStatus: boolean) => {
  try {
    await examApi.updateExamStatus(exam._id!, newStatus);
    ElMessage.success(`考试活动已${newStatus ? "启用" : "禁用"}`);
    fetchExams();
  } catch (error) {
    console.error("更新考试活动状态失败:", error);
    ElMessage.error("更新考试活动状态失败");
  }
};

// 查看详情
const handleView = (exam: IExam) => {
  openDialog("view", exam);
};

// 查看排名
const handleViewRanking = async (exam: IExam) => {
  currentExamInfo.value = exam;
  rankingDialogVisible.value = true;
  rankingLoading.value = true;

  try {
    // 获取排名数据
    const response = await examApi.getExamRanking(exam._id!);
    rankingData.value = response.data.rankings || [];
    console.log("排名数据:", rankingData.value);
  } catch (error) {
    console.error("获取排名数据失败:", error);
    ElMessage.error("获取排名数据失败");
    rankingData.value = [];
  } finally {
    rankingLoading.value = false;
  }
};

// 删除考试记录
const handleDeleteExamRecord = async (examRecord: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${examRecord.username}"的考试记录吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await examRecordApi.deleteExamRecord(examRecord._id);
    ElMessage.success("考试记录删除成功");

    // 重新获取排名数据
    await handleViewRanking(currentExamInfo.value);
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除考试记录失败:", error);
      ElMessage.error("删除考试记录失败");
    }
  }
};

// 过滤后的排名数据
const filteredRankingData = computed(() => {
  if (!rankingSearchKeyword.value) return rankingData.value;

  return rankingData.value.filter((item) =>
    item.username
      ?.toLowerCase()
      .includes(rankingSearchKeyword.value.toLowerCase())
  );
});

// 计算平均分
const calculateAverageScore = () => {
  if (rankingData.value.length === 0) return 0;
  const total = rankingData.value.reduce(
    (sum: number, item: any) => sum + item.score,
    0
  );
  return Math.round(total / rankingData.value.length);
};

// 获取排名样式
const getRankClass = (rank: number) => {
  if (rank === 1) return "rank-first";
  if (rank === 2) return "rank-second";
  if (rank === 3) return "rank-third";
  return "rank-normal";
};

// 获取正确率标签类型
const getAccuracyType = (score: number, totalScore: number) => {
  const percentage = (score / totalScore) * 100;
  if (percentage >= 90) return "success";
  if (percentage >= 80) return "primary";
  if (percentage >= 60) return "warning";
  return "danger";
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "未知时间";

  return new Date(dateTime).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 获取试卷名称
const getPaperName = (paper: any) => {
  return typeof paper === "object" ? paper.paper_name : "未知试卷";
};

// 组件挂载时获取数据
onMounted(() => {
  fetchExams();
  fetchAvailablePapers();
});
</script>

<template>
  <div class="activity-page">
    <!-- 搜索区域 -->
    <ElCard class="search-card">
      <div class="search-form">
        <ElSpace wrap>
          <ElInput
            v-model="searchForm.keyword"
            placeholder="搜索活动名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <Search />
            </template>
          </ElInput>

          <ElSelect
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <ElOption
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>

          <ElButton type="primary" :icon="Search" @click="handleSearch">
            搜索
          </ElButton>

          <ElButton @click="handleReset"> 重置 </ElButton>

          <ElButton type="primary" :icon="Plus" @click="openDialog('create')">
            创建考试活动
          </ElButton>
        </ElSpace>
      </div>
    </ElCard>

    <!-- 表格区域 -->
    <ElCard class="table-card">
      <ElTable
        :data="tableData"
        :loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <ElTableColumn prop="exam_name" label="活动名称" min-width="200" />

        <ElTableColumn prop="paper" label="试卷" width="150">
          <template #default="{ row }">
            {{ getPaperName(row.paper) }}
          </template>
        </ElTableColumn>

        <ElTableColumn prop="start_time" label="开始时间" width="150">
          <template #default="{ row }">
            {{ new Date(row.start_time).toLocaleString() }}
          </template>
        </ElTableColumn>

        <ElTableColumn prop="end_time" label="结束时间" width="150">
          <template #default="{ row }">
            {{ new Date(row.end_time).toLocaleString() }}
          </template>
        </ElTableColumn>

        <ElTableColumn prop="participation_limit" label="人数限制" width="100">
          <template #default="{ row }">
            {{ row.participation_limit || "无限制" }}
          </template>
        </ElTableColumn>

        <ElTableColumn label="考试状态" width="100">
          <template #default="{ row }">
            <ElTag :type="getExamStatus(row).type">
              {{ getExamStatus(row).text }}
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn prop="is_enabled" label="启用状态" width="100">
          <template #default="{ row }">
            <ElSwitch
              v-model="row.is_enabled"
              @change="handleStatusChange(row, $event)"
            />
          </template>
        </ElTableColumn>

        <ElTableColumn prop="creator" label="创建者" width="120">
          <template #default="{ row }">
            {{
              typeof row.creator === "object"
                ? row.creator.username
                : row.creator
            }}
          </template>
        </ElTableColumn>

        <ElTableColumn label="操作" width="380" fixed="right">
          <template #default="{ row }">
            <ElSpace>
              <ElButton
                type="primary"
                size="small"
                :icon="View"
                @click="handleView(row)"
              >
                详情
              </ElButton>

              <ElButton
                type="success"
                size="small"
                :icon="TrophyBase"
                @click="handleViewRanking(row)"
              >
                查看排名
              </ElButton>

              <ElButton
                type="primary"
                size="small"
                :icon="Edit"
                @click="openDialog('edit', row)"
              >
                编辑
              </ElButton>

              <ElButton
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </ElButton>
            </ElSpace>
          </template>
        </ElTableColumn>
      </ElTable>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </ElCard>

    <!-- 创建/编辑弹窗 -->
    <ElDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <ElForm
        ref="formRef"
        :model="examForm"
        :rules="formRules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <ElFormItem label="活动名称" prop="exam_name">
          <ElInput
            v-model="examForm.exam_name"
            placeholder="请输入活动名称"
            maxlength="50"
            show-word-limit
          />
        </ElFormItem>

        <ElFormItem label="活动描述">
          <ElInput
            v-model="examForm.description"
            type="textarea"
            placeholder="请输入活动描述"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </ElFormItem>

        <ElFormItem label="选择试卷" prop="paper">
          <ElSelect
            v-model="examForm.paper"
            placeholder="请选择试卷"
            style="width: 100%"
          >
            <ElOption
              v-for="paper in availablePapers"
              :key="paper._id"
              :label="`${paper.paper_name} (${paper.total_score}分, ${paper.duration}分钟)`"
              :value="paper._id"
            />
          </ElSelect>
        </ElFormItem>

        <ElFormItem label="开始时间" prop="start_time">
          <ElDatePicker
            v-model="examForm.start_time"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </ElFormItem>

        <ElFormItem label="结束时间" prop="end_time">
          <ElDatePicker
            v-model="examForm.end_time"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </ElFormItem>

        <ElFormItem label="人数限制">
          <ElInputNumber
            v-model="examForm.participation_limit"
            :min="0"
            :max="10000"
            placeholder="0表示无限制"
            style="width: 200px"
          />
          <span style="margin-left: 10px; color: #909399">0表示无限制</span>
        </ElFormItem>

        <ElFormItem label="允许重考">
          <ElSwitch
            v-model="examForm.allow_retake"
            active-text="是"
            inactive-text="否"
          />
        </ElFormItem>

        <ElFormItem label="启用状态">
          <ElSwitch
            v-model="examForm.is_enabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </ElFormItem>
      </ElForm>

      <template #footer v-if="dialogType !== 'view'">
        <ElSpace>
          <ElButton @click="closeDialog">取消</ElButton>
          <ElButton type="primary" @click="handleSave">保存</ElButton>
        </ElSpace>
      </template>
    </ElDialog>

    <!-- 排名弹窗 -->
    <ElDialog
      v-model="rankingDialogVisible"
      :title="`考试排名 - ${currentExamInfo?.exam_name || ''}`"
      width="80%"
      top="5vh"
      destroy-on-close
    >
      <div v-loading="rankingLoading" class="ranking-content">
        <!-- 统计信息 -->
        <div class="ranking-stats">
          <ElRow :gutter="20">
            <ElCol :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ rankingData.length }}</div>
                <div class="stat-label">参与人数</div>
              </div>
            </ElCol>
            <ElCol :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ calculateAverageScore() }}</div>
                <div class="stat-label">平均分</div>
              </div>
            </ElCol>
            <ElCol :span="6">
              <div class="stat-item">
                <div class="stat-value">
                  {{
                    rankingData.length > 0
                      ? Math.max(...rankingData.map((item) => item.score))
                      : 0
                  }}
                </div>
                <div class="stat-label">最高分</div>
              </div>
            </ElCol>
            <ElCol :span="6">
              <div class="stat-item">
                <div class="stat-value">
                  {{
                    rankingData.length > 0
                      ? Math.round(
                          (rankingData.filter(
                            (item) =>
                              (item.score / item.total_score) * 100 >= 60
                          ).length /
                            rankingData.length) *
                            100
                        )
                      : 0
                  }}%
                </div>
                <div class="stat-label">及格率</div>
              </div>
            </ElCol>
          </ElRow>
        </div>

        <!-- 搜索框 -->
        <div class="ranking-search">
          <ElInput
            v-model="rankingSearchKeyword"
            placeholder="搜索用户名"
            :prefix-icon="Search"
            clearable
            style="width: 300px"
          />
        </div>

        <!-- 排名表格 -->
        <ElTable
          :data="filteredRankingData"
          stripe
          border
          height="400"
          empty-text="暂无排名数据"
        >
          <ElTableColumn label="排名" width="80" align="center">
            <template #default="{ row }">
              <div class="rank-badge" :class="getRankClass(row.rank)">
                <TrophyBase v-if="row.rank <= 3" style="font-size: 16px" />
                <span v-else>{{ row.rank }}</span>
              </div>
            </template>
          </ElTableColumn>

          <ElTableColumn
            label="用户名"
            prop="username"
            width="150"
            show-overflow-tooltip
          />

          <ElTableColumn label="分数" width="120" align="center">
            <template #default="{ row }">
              <div class="score-display">
                <span class="score">{{ row.score }}</span>
                <span class="total">/ {{ row.total_score }}</span>
              </div>
            </template>
          </ElTableColumn>

          <ElTableColumn label="正确率" width="100" fixed align="center">
            <template #default="{ row }">
              <ElTag
                :type="getAccuracyType(row.score, row.total_score)"
                size="small"
              >
                {{ Math.round((row.score / row.total_score) * 100) }}%
              </ElTag>
            </template>
          </ElTableColumn>

          <ElTableColumn label="提交时间" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.submit_time) }}
            </template>
          </ElTableColumn>

          <ElTableColumn label="操作" width="100" align="center" fixed="right">
            <template #default="{ row }">
              <ElButton
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDeleteExamRecord(row)"
              >
                删除
              </ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
    </ElDialog>
  </div>
</template>

<style scoped>
.activity-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 排名弹窗样式 */
.ranking-content {
  min-height: 300px;
}

.ranking-stats {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.ranking-search {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.rank-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  font-weight: bold;
  font-size: 14px;
}

.rank-first {
  background: linear-gradient(45deg, #ffd700, #ffed4e);
  color: #333;
}

.rank-second {
  background: linear-gradient(45deg, #c0c0c0, #e0e0e0);
  color: #333;
}

.rank-third {
  background: linear-gradient(45deg, #cd7f32, #d4985a);
  color: #fff;
}

.rank-normal {
  background: #f5f7fa;
  color: #606266;
}

.score-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;
}

.score {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.total {
  font-size: 14px;
  color: #909399;
}
</style>
